<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="type === 'edit' ? $t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="550px" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'100px':'140px'" :rules="rules" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('管理员名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="offName" style="width:300px;" size='small' :disabled='type === "edit"' autoComplete="off"></el-input>
          <el-input v-emoji v-model="record.name" ref="editName" style="width:300px;" size='small' v-show="false" :disabled='type === "edit"' autoComplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('密码')" prop="password">
          <!-- <el-input v-emoji  v-model="record.password" style="width:300px;" size='small' type="password" autocomplete="new-password"></el-input> -->
          <el-input v-emoji v-model="record.password" ref="password" style="width:300px;" size='small' @focus="handleFocus" @blur="handleBlur" class="inputPsd"></el-input>
          <div class="adminConfigPassword">{{$t('密码至少8位，至多24位，至少使用数字、小写字母、大写字母、特殊符号中的三种，并且密码字符中不应包含管理员名称！')}}</div>
        </el-form-item>
        <el-form-item :label="$t('确认密码')" prop="password_agree">
          <!-- <el-input v-emoji  v-model="record.password_agree" style="width:300px;" size='small' type="password" autocomplete="new-password"></el-input> -->
          <el-input v-emoji v-model="record.password_agree" ref="passwordConfirm" style="width:300px;" size='small' @focus="handleFocus" @blur="handleBlur" class="inputPsd"></el-input>
        </el-form-item>
        <el-form-item :label="$t('管理员所属角色')" v-if="!roleNoChange.includes(record.name) || type !== 'edit'" prop="role">
          <el-select size="medium" v-model="record.role" ref="recordRole" :placeholder="$t('选择角色')" :disabled='type === "edit"' style="width:300px;">
            <el-option v-for="item in roleList" :key="item.id" :label="$t(item.name)" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { editPassword, editRole, addAdmin } from '@/api/system/adminConfig/administrators'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'AdminConfigDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入管理员名称')))
      } else {
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入密码')))
      } else {
        callback()
      }
    }
    var validatePasswordAgree = (rule, value, callback) => {
      if (this.record.password !== this.record.password_agree) {
        callback(new Error(this.$t('密码两次输入的不一致,请仔细确认!')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        name: '',
        password: '',
        password_agree: '',
        role: 2
      },
      recordCopy: {
        name: '',
        password: '',
        password_agree: '',
        role: 2
      },
      lang: this.$i18n.locale,
      role_old: '',
      type: '',
      roleList: [
        // { id: 1, name: '超级管理员' },
        { id: 2, name: '审计管理员' },
        { id: 3, name: '系统管理员' },
        { id: 4, name: '配置管理员' }
      ],
      role: {
        '超级管理员': 1,
        '审计管理员': 2,
        '系统管理员': 3,
        '配置管理员': 4
      },
      roleNoChange: ['admin', 'auditadmin', 'sysadmin', 'cfgadmin'],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        password: [{ required: false, validator: validatePassword, trigger: 'blur' }],
        password_agree: [{ required: false, validator: validatePasswordAgree, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (data, type) {
      this.type = type
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['password', 'passwordConfirm', 'offName', 'editName']
        inputClass(this.$refs, data)
        if (!this.roleNoChange.includes(this.record.name) || this.type !== 'edit') {
          const selectData = ['recordRole']
          selectClass(this.$refs, selectData)
        }
      })
      if (data) {
        this.record = Object.assign(this.record, data)
        this.record.role = this.role[data.role]
        this.role_old = this.role[data.role]
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.record.port = Number(this.record.port)
          if (this.type === 'edit') {
            if (this.roleNoChange.includes(this.record.name)) {
              editPassword({ name: this.record.name, password: this.record.password }).then(res => {
                if (res.status === 0) {
                  this.$messages.success(this.$t('编辑成功'))
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              if (this.role_old === this.record.role) {
                editPassword({ name: this.record.name, password: this.record.password }).then(res => {
                  this.$messages.success(this.$t('编辑成功'))
                  this.close()
                  this.$parent.listData()
                })
              } else {
                Promise.all([
                  editPassword({ name: this.record.name, password: this.record.password }),
                  editRole({ name: this.record.name, role: this.record.role })
                ]).then(res => {
                  /* 你的逻辑代码 */
                  if (res[0].status === 0 && res[1].status === 0) {
                    this.$messages.success(this.$t('编辑成功'))
                    this.close()
                    this.$parent.listData()
                  }
                })
              }
              // editPassword({ name: this.record.name, password: this.record.password }).then(res => {
              //   if (res.status === 0) {
              //     editRole({ name: this.record.name, role: this.record.role }).then(res => {
              //       if (res.status === 0) {
              //         this.$message({
              //           message: this.$t('编辑成功'),
              //           type: 'success'
              //         })
              //       }
              //     })
              //   }
              // })
            }
          } else {
            addAdmin(this.record).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('添加成功'))
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.$parent.adminConfigDialogVisible = false
      this.type = ''
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    handleFocus () {
      this.$refs.password = 'password'
    },
    handleBlur () {
      this.$refs.password = 'text'
    }
  }
}
</script>
<style lang="scss" scoped>
.adminConfigPassword {
  font-size: 12px;
  line-height: 20px;
  color: #999;
}

.inputPsd {
  -webkit-text-security: disc;
}
</style>
